var express = require('express');
var router = express.Router();
var md5 = require("md5");
var userDAO = require("../bin/db/userDAO.js");
var cartDAO = require("../bin/db/cartDAO.js");
var session = require("express-session");
router.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}));
// 导入并配置multer
var multer = require("multer");
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/avatar');
  },
  filename: function (req, file, cb) {
    var fileName = req.session.user._id + "." + file.mimetype.split("/")[1];
    req.userAvatar = fileName;
    cb(null, fileName);
  }
});
var upload = multer({ storage: storage });

// 注册
router.post("/regist", (req, res) => {
  userDAO.findOne({ username: req.body.username })
    .then(data => {
      if (data) {
        res.json({ err: 1, msg: "用户名已被占用" });
        return;
      } else if (!data) {
        var reg = /^\w{2,12}$/;
        if (!reg.test(req.body.username)) {
          res.json({ err: 3, msg: "账号格式错误" });
          return;
        } else if (!reg.test(req.body.psw)) {
          res.json({ err: 4, msg: "密码格式错误" });
          return;
        } else if (req.body.psw !== req.body.confirm) {
          res.json({ err: 5, msg: "两次输入密码不一致" });
          return;
        } else if (req.session.captcha !== req.body.captcha.toUpperCase()) {
          res.json({ err: 2, msg: "验证码错误" });
          delete req.session.captcha;
          return;
        } else {
          var u = new userDAO({
            username: req.body.username,
            psw: req.body.psw,
            avatar: req.userAvatar,
            cart: []
            // cart: []
          });
          u.psw = md5(u.psw);
          u.save()
            .then(data => {
              res.json({ err: 0, msg: "注册成功" });
            })
        }
      }
    })
});

// 登录
router.post("/login", function (req, res) {
  userDAO.findOne({ username: req.body.username })
    .then(data => {
      if (!data) {
        res.json({ err: 1, msg: "用户不存在" });

      } else {
        if (md5(req.body.psw) == data.psw) {
          req.session.user = data;
          res.json({ err: 0, msg: "登录成功" });
        } else {
          res.json({ err: 2, msg: "密码错误" });
        }
      }
    });
});


// 验证码
var ccap = require("ccap");
var captcha = ccap({
  width: 80,
  height: 30,
  offset: 20,
  quality: 80,
  fontsize: 27,
  generate: function () {
    var sourceStr = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
    var text = "";
    for (var i = 0; i < 4; i++) {
      var index = Math.floor(Math.random() * sourceStr.length);
      var ch = sourceStr[index];
      text += ch;
    }
    return text;
  }

});

router.get("/captcha", (req, res) => {
  var arr = captcha.get();

  console.log(arr[0]);
  req.session.captcha = arr[0];

  res.set("Content-Type", "image/jpeg");
  res.send(arr[1]);

});

//判断是否已登录的接口
router.get("/isLogin", (req, res) => {
  if (req.session.user) {
    userDAO.findOne({ _id: req.session.user._id })
      .then(data => {
        var isLogin = {
          isLogin: true,
        }
        res.json({ err: 0, isLogin })
      })
  } else {
    var isLogin = {
      isLogin: false,
    }
    res.json({ err: 1, isLogin })
  }
});


router.get("/exit", function (req, res) {

  req.session.user = "";

  res.json({ err: 0, msg: "退出成功" });

})


// 头像
router.post("/upload", upload.single("header"), (req, res) => {
  userDAO.findOne({ username: req.session.user.username }, function (err, data) {
    data.avatar = req.userAvatar;
    data.save(function (err) {
      res.json({ err: 0, msg: "上传成功" });
    });
  });


});

router.post("/img", (req, res) => {
  userDAO.findOne({ _id: req.session.user._id })
    .then(data => {
      res.json({ data: data })
    })
})

// 添加购物车
router.post("/add", function (req, res) {
  if (req.session.user) {
    cartDAO.findOne({ id: req.body.id, userid: req.session.user._id })
      .then(data => {
        if (data) {
          data.num++;
          data.save()
           res.json({err:0})
        } else {
          var u = new cartDAO({
            id: req.body.id,
            name: req.body.name,
            detail: req.body.detail,
            price: req.body.price,
            img: req.body.img,
            bigclasses: req.body.bigclasses,
            littleclasses: req.body.littleclasses,
            num: 1,
            check: true,
            userid: req.session.user._id

          })
          u.save()
            .then(data => {
              res.json({err:0})
              userDAO.findOne({ _id: req.session.user._id })
                .then(data => {
                  data.cart.push(u._id);
                  data.save()

                })
            })
        }

      })
  } else {
    res.json({ err:1})
  }
})

// 购物车内容
router.post("/cartlist", function (req, res) {
  // console.log(123)
  userDAO.findOne({ _id: req.session.user._id }).populate("cart")
    .then(data => {
      res.json({ data })
    })

});


router.post("/decrease", function (req, res) {
  // console.log(123)
  cartDAO.findOne({ _id: req.body._id })
    .then(data => {
      data.num--
      data.save()
    })

});

router.post("/addnum", function (req, res) {
  // console.log(123)
  cartDAO.findOne({ _id: req.body._id })
    .then(data => {
      data.num++
      data.save()
    })

});

// 购物车删除
router.post("/delate", function (req, res) {
  cartDAO.remove({ _id: req.body._id })
  .then(data=>{
      res.json({err:0})
  })
    
  });

module.exports = router;
